package com.videoweb.controller;

import com.videoweb.model.Danmaku;
import com.videoweb.service.DanmakuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/danmaku")
@CrossOrigin
public class DanmakuController {
    
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DanmakuController.class);
    
    @Autowired
    private DanmakuService danmakuService;
    
    @PostMapping
    public ResponseEntity<Danmaku> createDanmaku(
            @RequestParam Long videoId,
            @RequestParam String content,
            @RequestParam Double timestamp,
            @RequestParam String position,
            @RequestParam String color,
            @RequestParam Integer size,
            @RequestParam(required = false) String sender,
            HttpServletRequest request) {
        
        // 确定发送者身份：已登录用户 vs 匿名用户
        String actualSender = determineActualSender(sender, request);
        
        log.debug("Creating danmaku for video {} by sender: {}", videoId, actualSender);
        
        Danmaku danmaku = danmakuService.createDanmaku(videoId, content, timestamp, position, color, size, actualSender);
        return ResponseEntity.ok(danmaku);
    }
    
    @GetMapping("/video/{videoId}")
    public ResponseEntity<List<Danmaku>> getDanmakusByVideoId(@PathVariable Long videoId) {
        return ResponseEntity.ok(danmakuService.getDanmakusByVideoId(videoId));
    }
    
    /**
     * 确定实际的弹幕发送者
     * 如果用户已登录，使用用户名；如果未登录，使用匿名标识
     */
    private String determineActualSender(String providedSender, HttpServletRequest request) {
        // 首先检查用户是否已登录
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        
        // 检查Session中的用户信息
        HttpSession session = request.getSession(false);
        if (session != null) {
            Boolean authenticated = (Boolean) session.getAttribute("authenticated");
            if (Boolean.TRUE.equals(authenticated)) {
                Object sessionUser = session.getAttribute("currentUser");
                if (sessionUser != null) {
                    // 用户已登录，使用登录用户名
                    String username = ((com.videoweb.model.User) sessionUser).getUsername();
                    log.debug("Logged in user sending danmaku: {}", username);
                    return username;
                }
            }
        }
        
        // 检查Security Context
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            log.debug("Authenticated user sending danmaku: {}", auth.getName());
            return auth.getName();
        }
        
        // 用户未登录，生成匿名标识
        String anonymousSender;
        if (providedSender != null && !providedSender.trim().isEmpty()) {
            // 使用前端提供的匿名名称，但添加匿名标识
            anonymousSender = "匿名用户-" + providedSender.trim();
        } else {
            // 生成随机匿名标识
            anonymousSender = "匿名用户-" + generateAnonymousId();
        }
        
        log.debug("Anonymous user sending danmaku: {}", anonymousSender);
        return anonymousSender;
    }
    
    /**
     * 生成匿名用户ID
     */
    private String generateAnonymousId() {
        return String.format("%04d", (int)(Math.random() * 10000));
    }
}
